import 'package:easy_device_info/easy_device_info.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:get/get.dart';
import 'package:loader_overlay/loader_overlay.dart';
import 'package:realm/realm.dart';
import 'package:sgy_flutter/api_service.dart';
import 'package:sgy_flutter/ble/ble_manager.dart';
import 'package:sgy_flutter/ble/right_ble_manager.dart';
import 'package:sgy_flutter/database/device_entity.dart';
import 'package:sgy_flutter/page/home/view.dart';
import 'package:sgy_flutter/theme.dart';
import 'dart:ui' as ui;

import 'i18n/i18n.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
  ]);
  SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark.copyWith(
    statusBarColor: Colors.transparent,
    systemNavigationBarColor: Colors.white,
  ));
  // Get.;
  await initServices();

  /// 等待服务初始化.
  runApp(const MyApp());
}

Future initServices() async {
  print('starting services ...');
  await DeviceInfoService().init();

  ///这里是你放get_storage、hive、shared_pref初始化的地方。
  ///或者moor连接，或者其他什么异步的东西。
  Get.put(BleManager());
  BleManager bleService = Get.find();
  await bleService.init();
  Get.put(RightBleManager());
  RightBleManager rightBleManager = Get.find();
  await rightBleManager.init();

  Get.put(ApiService());
  Get.put(Realm(Configuration.local([RealmDeviceEntity.schema])));
  print('All services started...');
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return LoadingApp(
      child: GetMaterialApp(
        title: '思各异'.tr,
        debugShowCheckedModeBanner: false,
        translations: i18n(),
        locale: ui.window.locale,
        fallbackLocale: Locale('en', 'US'),
        // 添加一个回调语言选项，以备上面指定的语言翻译不存在
        defaultTransition: Transition.cupertino,
        transitionDuration: Duration(milliseconds: 300),
        popGesture: false,
        builder: ApiService.baseURL != "https://app.sigeyi.com/sgy/admin/api/"
            ? (context, child) {
                return Stack(
                  children: [
                    child!,
                    Align(
                      alignment: Alignment.topCenter,
                      child: Badge(
                        label: Text("测试版"),
                      ),
                    ),
                  ],
                );
              }
            : null,
        theme: globalAppThemeData,
        home: HomePage(),
      ),
    );
  }
}

class LoadingApp extends StatelessWidget {
  final Widget child;

  const LoadingApp({super.key, required this.child});

  @override
  Widget build(BuildContext context) {
    return GlobalLoaderOverlay(
      overlayColor: Colors.black38,
      overlayWidgetBuilder: (progress) {
        return Center(
          child: Container(
            constraints: BoxConstraints(
                minWidth: 120,
                minHeight: 120,
                maxWidth: Get.width,
                maxHeight: Get.height),
            padding: EdgeInsets.all(12),
            margin: EdgeInsets.symmetric(vertical: 60, horizontal: 40),
            decoration: BoxDecoration(
              color: Colors.black54,
              borderRadius: BorderRadius.circular(12),
            ),
            child: IntrinsicWidth(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  SpinKitFadingCircle(
                    color: Colors.white,
                    size: 50.0,
                  ),
                  Visibility(
                    visible: progress != null,
                    child: Text(
                      "$progress",
                      style: TextStyle(fontSize: 16, color: Colors.white),
                    ).marginOnly(top: 12),
                  ),
                ],
              ),
            ),
          ),
        );
      },
      child: child,
    );
  }
}
